package com.kanshu.ksgb.fastread.doudou.module.book.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dl7.recycler.helper.RecyclerViewHelper;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.BaseAdListener;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.CacheManager;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideImageLoader;
import com.kanshu.ksgb.fastread.doudou.common.supertextview.SuperTextView;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.BookShelfGoodBookAdapter;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.BookShelfGoodPresentAdapter;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.BookShelfRecentReadAdapter;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.RecentBookInfo;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ShelfGoodBook;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ShelfGoodPresent;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ShelfTopData;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.BookUtils;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.listener.BookcaseTopListener;
import com.kanshu.ksgb.fastread.doudou.common.view.CYStickyNavLayouts;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Title:
 * Description:
 * Copyright: Copyright(c)2018
 * Company: 看书网
 * CreateTime: 2018/5/28 10:14
 *
 * @author EvanHe
 * @version 3.0
 */
public class AdBookShelfHeaderLayout extends LinearLayout {

    @BindView(R.id.recycler_good_book)
    RecyclerView mRecyclerGoodBook;
    @BindView(R.id.good_book_layout)
    RelativeLayout mGoodBookLayout;
    @BindView(R.id.recycler_good_present)
    RecyclerView mRecyclerGoodPresent;
    @BindView(R.id.good_present_layout)
    RelativeLayout mGoodPresentLayout;
    @BindView(R.id.recycler_recent_read)
    RecyclerView mRecyclerRecentRead;
    @BindView(R.id.recent_read_layout)
    RelativeLayout mRecentReadLayout;
    @BindView(R.id.no_recent_read_layout)
    LinearLayout mNoRecentReadLayout;
    @BindView(R.id.recycler_good_book1)
    RecyclerView mRecyclerGoodBook1;
    @BindView(R.id.base_refresh4)
    CYStickyNavLayouts mRefreshRelativeLayout4;

    private View ContentView;

    RelativeLayout mFirstRootContainer;
    TextView mFirstBookTitle;
    TextView mFirstBookDesc;
    TextView mFirstAuthor;
    TextView mFirstBookLabel;
    SuperTextView mFirstBookStatus;
    ImageView mFirstBookCover;
    TextView mFirstDownloadCount;
    LinearLayout mFirstBottomContainer;


    Context mContext;
    List<ShelfGoodPresent> mGoodPresentInfos = new ArrayList<>();
    BookShelfGoodPresentAdapter mGoodPresentAdapter;
    List<ShelfGoodBook> mGoodBookInfos = new ArrayList<>();
    BookShelfGoodBookAdapter mGoodBookAdapter;
    List<RecentBookInfo> mRecentBookInfos = new ArrayList<>();
    BookShelfRecentReadAdapter mRecentReadAdapter;
    List<ShelfGoodBook> mGoodBookInfos1 = new ArrayList<>();
    BookShelfGoodBookAdapter mGoodBookAdapter1;

    BookInfo mTopBookInfo;
    BookcaseTopListener mTopListener;
    List<ShelfGoodBook> first_row = new ArrayList<>();
    List<ShelfGoodBook> second_row = new ArrayList<>();

    public AdBookShelfHeaderLayout(Context context) {
        super(context);
        init(context);
    }

    public AdBookShelfHeaderLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public AdBookShelfHeaderLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void setTopListener(BookcaseTopListener topListener) {
        mTopListener = topListener;
    }

    private void init(Context context) {
        mContext = context;
        setOrientation(VERTICAL);
        ContentView = LayoutInflater.from(getContext()).inflate(R.layout.shelf_recent_read_layout, this);
        ButterKnife.bind(ContentView);
        //好礼相送
        mGoodPresentAdapter = new BookShelfGoodPresentAdapter(mContext, mGoodPresentInfos);
        RecyclerViewHelper.initRecyclerViewH(mContext, mRecyclerGoodPresent, mGoodPresentAdapter);
        CYStickyNavLayouts refreshRelativeLayout = ContentView.findViewById(R.id.base_refresh1);
        /*View goodPresentFooter = LayoutInflater.from(context).inflate(R.layout.layout_more, this, false);
        TextView moreTv = goodPresentFooter.findViewById(R.id.tv);
        moreTv.setText("发现更多");
        goodPresentFooter.setOnClickListener(v -> {
            AppMainActivity.actionStart((Activity) mContext, AppMainActivity.TAB_FIND);
            AdPresenter.Companion.pvuvStatics(R.string.TOPFUNCTION_FXGENGDUO);
        });
        mGoodPresentAdapter.addFooterViewWrapContent(goodPresentFooter);*/
        refreshRelativeLayout.hideMoreText();
        refreshRelativeLayout.setOnStartActivity(() -> {
            AdPresenter.Companion.pvuvStatics(R.string.TOPFUNCTION_FXGENGDUO);
            ARouterUtils.toActivity(ARouterConfig.HOME_PAGE, "tab_index", String.valueOf(ARouterConfig.HomePageParams.TAB_FIND));
        });
        //好书推荐第一排
        mGoodBookAdapter = new BookShelfGoodBookAdapter(mContext, mGoodBookInfos);
        RecyclerViewHelper.initRecyclerViewH(mContext, mRecyclerGoodBook, mGoodBookAdapter);
        CYStickyNavLayouts refreshRelativeLayout2 = ContentView.findViewById(R.id.base_refresh2);
        View goodBookFooter = LayoutInflater.from(context).inflate(R.layout.layout_more, this, false);
        mGoodBookAdapter.addFooterViewWrapContent(goodBookFooter);
        goodBookFooter.setOnClickListener(v -> {
            ARouterUtils.toActivity(ARouterConfig.HOME_PAGE, "tab_index", String.valueOf(ARouterConfig.HomePageParams.TAB_BOOK_CITY));
                    AdPresenter.Companion.pvuvStatics(R.string.HSTUIJIAN_CKGENGDUO);
                }
        );
        refreshRelativeLayout2.setOnStartActivity(() -> {
            ARouterUtils.toActivity(ARouterConfig.HOME_PAGE, "tab_index", String.valueOf(ARouterConfig.HomePageParams.TAB_BOOK_CITY));
            Log.i("test", "onNegtiveRefres2");
            AdPresenter.Companion.pvuvStatics(R.string.HSTUIJIAN_CKGENGDUO);
        });
        //最近阅读
        mRecentReadAdapter = new BookShelfRecentReadAdapter(mContext, mRecentBookInfos);
        RecyclerViewHelper.initRecyclerViewH(mContext, mRecyclerRecentRead, mRecentReadAdapter);
        CYStickyNavLayouts refreshRelativeLayout3 = ContentView.findViewById(R.id.base_refresh3);
        View mRecentReadFooter = LayoutInflater.from(context).inflate(R.layout.layout_more, this, false);
        mRecentReadAdapter.addFooterViewWrapContent(mRecentReadFooter);
        mRecentReadFooter.setOnClickListener(v -> ARouterUtils.toActivity(ARouterConfig.RECENT_READ_LIST));
        refreshRelativeLayout3.setOnStartActivity(() -> {
            Log.i("test", "onNegtiveRefres3");
            ARouterUtils.toActivity(ARouterConfig.RECENT_READ_LIST);
        });
        //好书推荐第二排
        mGoodBookAdapter1 = new BookShelfGoodBookAdapter(mContext, mGoodBookInfos1);
        RecyclerViewHelper.initRecyclerViewH(mContext, mRecyclerGoodBook1, mGoodBookAdapter1);
        View goodBookFooter1 = LayoutInflater.from(context).inflate(R.layout.layout_more, this, false);
        mGoodBookAdapter1.addFooterViewWrapContent(goodBookFooter1);
        goodBookFooter1.setOnClickListener(v -> {
            ARouterUtils.toActivity(ARouterConfig.HOME_PAGE, "tab_index", String.valueOf(ARouterConfig.HomePageParams.TAB_BOOK_CITY));
                    AdPresenter.Companion.pvuvStatics(R.string.HSTUIJIAN_CKGENGDUO2);
                }
        );
        mRefreshRelativeLayout4.setOnStartActivity(() -> {
            ARouterUtils.toActivity(ARouterConfig.HOME_PAGE, "tab_index", String.valueOf(ARouterConfig.HomePageParams.TAB_BOOK_CITY));AdPresenter.Companion.pvuvStatics(R.string.HSTUIJIAN_CKGENGDUO2);
        });
    }

    @SuppressLint("SetTextI18n")
    public void setTopBookInfo(BookInfo topBookInfo) {
        if (mFirstRootContainer == null) {
            mFirstRootContainer = ContentView.findViewById(R.id.root_container);
            mFirstBookTitle = mFirstRootContainer.findViewById(R.id.book_title);
            mFirstBookDesc = mFirstRootContainer.findViewById(R.id.book_desc);
            mFirstAuthor = mFirstRootContainer.findViewById(R.id.author);
            mFirstBookLabel = mFirstRootContainer.findViewById(R.id.book_label);
            mFirstBookStatus = mFirstRootContainer.findViewById(R.id.book_status);
            mFirstBookCover = mFirstRootContainer.findViewById(R.id.cover);
            mFirstDownloadCount = mFirstRootContainer.findViewById(R.id.download_chapter_count);
            mFirstBottomContainer = mFirstRootContainer.findViewById(R.id.bottom_container);
            mFirstRootContainer.setOnClickListener(v -> {
                if (mTopListener != null)
                    mTopListener.setOnClickListener(mTopBookInfo);
            });
            mFirstRootContainer.setOnLongClickListener(view1 -> {
                if (mTopListener != null) {
                    mTopListener.setOnLongClickListener();
                }
                return false;
            });
        }
        mFirstRootContainer.setVisibility(topBookInfo != null && !BookInfo.SHELF_ADD_FLAG.equals(topBookInfo.book_id) ? VISIBLE : GONE);
        if (topBookInfo != null) {
            mTopBookInfo = topBookInfo;
            mFirstBookTitle.setText(mTopBookInfo.book_title);
            mFirstBookDesc.setText(mTopBookInfo.book_intro);
            mFirstAuthor.setText(mTopBookInfo.author_name);
            mFirstBookLabel.setText(BookUtils.getBookLabel(mTopBookInfo));
            BookUtils.setStatusBg(mFirstBookStatus, mTopBookInfo);
            GlideImageLoader.load(mTopBookInfo.cover_url, mFirstBookCover);
            int download_count = MMKVUserManager.getInstance().getBookDownloadChapterCount(mTopBookInfo.book_id);
            if(download_count == 0){
                DisplayUtils.gone(mFirstDownloadCount);
            }else{
                DisplayUtils.visible(mFirstDownloadCount);
                mFirstDownloadCount.setText("已下载"  + (TextUtils.equals(String.valueOf(download_count), mTopBookInfo.chapter_count) ? "" : download_count + "章"));
            }
        }
    }

    /**
     * 删除下载书籍成功，刷新一下最近阅读
     */
    public void refreshRecentRead() {
        mRecentReadAdapter.notifyDataSetChanged();
    }

    public void refresh(ShelfTopData info) {
        if (info == null) {
            return;
        }
        //好礼相送
        if (Utils.isEmptyList(info.haoli_xiangsong)) {
            mGoodPresentLayout.setVisibility(GONE);
        } else {
            mGoodPresentInfos.clear();
            mGoodPresentInfos.addAll(info.haoli_xiangsong);
            mGoodPresentAdapter.notifyDataSetChanged();
            mGoodPresentLayout.setVisibility(VISIBLE);
        }

        //编辑好书
        if (Utils.isEmptyList(info.bianji_haoshu)) {
            mGoodBookLayout.setVisibility(GONE);
            mRefreshRelativeLayout4.setVisibility(GONE);
        } else {
            mGoodBookInfos.clear();
            mGoodBookInfos1.clear();
            first_row.clear();
            second_row.clear();
            int size = info.bianji_haoshu.size();
            for (int i = 0; i < size; i++) {
                info.bianji_haoshu.get(i).position = i;
                //好书推荐第一排显示6本书
                if (i < 6) {
                    first_row.add(info.bianji_haoshu.get(i));
                } else {
                    second_row.add(info.bianji_haoshu.get(i));
                }
            }
            mGoodBookInfos.addAll(first_row);
            mGoodBookAdapter.notifyDataSetChanged();
            mGoodBookLayout.setVisibility(VISIBLE);
            if (!Utils.isEmptyList(second_row)) {
                mGoodBookInfos1.addAll(second_row);
                mGoodBookAdapter1.notifyDataSetChanged();
                mRefreshRelativeLayout4.setVisibility(VISIBLE);
            } else {
                mRefreshRelativeLayout4.setVisibility(GONE);
            }
            adResult1 = false;
            adResult2 = false;
            adResult3 = false;
            AdUtils.fetchAdUtil((Activity) mContext, null, null,
                    ADConfigBean.POSITION_BIANJIHAOSHU_SJ_1, AdStyleBean.BOOK_COVER_STYLE, R.layout.item_shelf_good_book_layout,
                    new BaseAdListenerImplGoodBook(ADConfigBean.POSITION_BIANJIHAOSHU_SJ_1));
            if (size > 1) {
                AdUtils.fetchAdUtil((Activity) mContext, null, null,
                        ADConfigBean.POSITION_BIANJIHAOSHU_SJ_2, AdStyleBean.BOOK_COVER_STYLE, R.layout.item_shelf_good_book_layout,
                        new BaseAdListenerImplGoodBook(ADConfigBean.POSITION_BIANJIHAOSHU_SJ_2));
            }
            if (size > 3) {
                AdUtils.fetchAdUtil((Activity) mContext, null, null,
                        ADConfigBean.POSITION_BIANJIHAOSHU_SJ_3, AdStyleBean.BOOK_COVER_STYLE, R.layout.item_shelf_good_book_layout,
                        new BaseAdListenerImplGoodBook(ADConfigBean.POSITION_BIANJIHAOSHU_SJ_3));
            }
        }

        //最近阅读
        if (Utils.isEmptyList(info.zuijin_yuedu)) {
            mRecentReadLayout.setVisibility(GONE);
            mNoRecentReadLayout.setVisibility(VISIBLE);
        } else {
            mRecentBookInfos.clear();
            mRecentBookInfos.addAll(info.zuijin_yuedu);
            mRecentReadAdapter.notifyDataSetChanged();
            mRecentReadLayout.setVisibility(VISIBLE);
            mNoRecentReadLayout.setVisibility(GONE);
        }
    }

    public void refreshRecentRead(List<RecentBookInfo> recentBookInfo) {
        if (Utils.isEmptyList(recentBookInfo)) {
            mRecentReadLayout.setVisibility(GONE);
            mNoRecentReadLayout.setVisibility(VISIBLE);
        } else {
            mRecentBookInfos.clear();
            mRecentBookInfos.addAll(recentBookInfo);
            mRecentReadAdapter.notifyDataSetChanged();
            mRecentReadLayout.setVisibility(VISIBLE);
            mNoRecentReadLayout.setVisibility(GONE);
            mRecyclerRecentRead.scrollToPosition(0);
        }
    }

    private boolean adResult1 = false; // position1加载结果
    private boolean adResult2 = false; // position2加载结果
    private boolean adResult3 = false; // position3加载结果

    class BaseAdListenerImplGoodBook implements BaseAdListener {

        int positionId;

        BaseAdListenerImplGoodBook(int positionId) {
            this.positionId = positionId;
        }

        @Override
        public void onAdLoadSucceeded(@org.jetbrains.annotations.Nullable View view) {
            if (view == null) {
                Log.i("test", "adView = null");
            }
            int index1 = 0;
            int index2 = 0;
            int index3 = 0;
            ShelfGoodBook adItem = new ShelfGoodBook();
            adItem.adView = view;
            switch (positionId) {
                case ADConfigBean.POSITION_BIANJIHAOSHU_SJ_1:
                    //ad 1 ,add to position 0
                    if (adResult1) {
                        mGoodBookAdapter.removeItem(index1);
                    }
                    mGoodBookAdapter.addItem(adItem, index1);
                    mRecyclerGoodBook.scrollToPosition(0);
                    adResult1 = true;
                    break;
                case ADConfigBean.POSITION_BIANJIHAOSHU_SJ_2:
                    index2 += 2;
                    if (adResult1) {
                        index2++;
                    }
                    if (adResult2) {
                        mGoodBookAdapter.removeItem(index2);
                    }
                    mGoodBookAdapter.addItem(adItem, index2);
                    adResult2 = true;
                    break;
                case ADConfigBean.POSITION_BIANJIHAOSHU_SJ_3:
                    index3 += 4;
                    if (adResult1) {
                        index3++;
                    }
                    if (adResult2) {
                        index3++;
                    }
                    if (adResult3) {
                        mGoodBookAdapter.removeItem(index3);
                    }
                    mGoodBookAdapter.addItem(adItem, index3);
                    adResult3 = true;
                    break;
            }
        }

        @Override
        public void onAdLoadFailed() {
        }

        @Override
        public void onAdClicked() {
        }

        @Override
        public void onADClosed() {
        }

        @Override
        public void onBackAd(@NotNull Object ad) {
        }
    }
}
